package com.xqboss.apps.service.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.constant.Config;
import com.xqboss.apps.constant.LockKey;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.convert.order.OrderConverter;
import com.xqboss.apps.domain.order.*;
import com.xqboss.apps.domain.user.SysUserWallet;
import com.xqboss.apps.dto.order.*;
import com.xqboss.apps.domain.order.OrderGift;
import com.xqboss.apps.domain.order.OrderItem;
import com.xqboss.apps.domain.order.OrderMain;
import com.xqboss.apps.domain.order.PayApply;
import com.xqboss.apps.dto.order.CreateOrderDto;
import com.xqboss.apps.dto.order.OrderStatisticsDto;
import com.xqboss.apps.dto.order.WebOrderListDto;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.order.OrderStatusEnum;
import com.xqboss.apps.enums.order.OrderTypeEnum;
import com.xqboss.apps.enums.order.PayStatusEnum;
import com.xqboss.apps.enums.order.RefundStatusEnum;
import com.xqboss.apps.enums.user.PayTypeEnum;
import com.xqboss.apps.enums.user.UserWalletEnum;
import com.xqboss.apps.enums.user.WalletChangeTypeEnum;
import com.xqboss.apps.mapper.order.OrderMainMapper;
import com.xqboss.apps.mapper.order.OrderQuickCopyRecordMapper;
import com.xqboss.apps.mapper.order.QuickCopyRecordMapper;
import com.xqboss.apps.service.order.pay.impl.WalletPayExecutor;
import com.xqboss.apps.service.order.type.OrderTypeExecutor;
import com.xqboss.apps.service.order.status.OrderStatusExecutor;
import com.xqboss.apps.service.sys.ConfigService;
import com.xqboss.apps.vo.order.*;
import com.xqboss.apps.service.user.YeepayWalletService;
import com.xqboss.apps.vo.order.AppOrderListExportVo;
import com.xqboss.apps.service.user.SysUserWalletService;
import com.xqboss.apps.vo.order.OrderStatisticsVo;
import com.xqboss.apps.vo.order.AppOrderListExportVo;
import com.xqboss.apps.vo.pay.PayInfoVo;
import com.xqboss.common.constant.HttpStatus;
import com.xqboss.common.constant.UserConstants;
import com.xqboss.common.core.domain.PageList;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysDictData;
import com.xqboss.common.core.domain.model.LoginUser;
import com.xqboss.common.core.mq.MqSender;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.core.redis.lock.LockObject;
import com.xqboss.common.core.redis.lock.LockValue;
import com.xqboss.common.core.redis.lock.RedisLock;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.SecurityUtils;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.system.mapper.SysDictDataMapper;
import com.xqboss.system.service.ISysConfigService;
import com.xqboss.system.service.ISysUserService;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.poi.ss.formula.functions.Now;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单服务
 * </p>
 *
 * @author Trent
 * @date 2023/8/21
 */
@Service
public class OrderService extends ServiceImpl<OrderMainMapper, OrderMain> {

    @Autowired
    private Map<String, OrderStatusExecutor> orderStatusExecutor;

    @Autowired
    private Map<String, OrderTypeExecutor> createOrderExecutor;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    @Lazy
    private PayApplyService payApplyService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    @Lazy
    private SysUserWalletService userWalletService;

    @Lazy
    @Autowired
    private MqSender mqSender;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private SysUserWalletService sysUserWalletService;
    @Autowired
    private OrderQuickCopyRecordService orderQuickCopyRecordService;
    @Autowired
    private OrderConverter orderConverter;

    @Autowired
    private QuickCopyRecordMapper quickCopyRecordMapper;

    @Autowired
    @Lazy
    private WalletPayExecutor walletPayExecutor;


    @Autowired
    private OrderDivideService orderDivideService;

    @Autowired
    private OrderGiftService orderGiftService;

    @Autowired
    private YeepayWalletService yeepayWalletService;


    /**
     * 检测用户是否恶意锁单
     * @param userId
     */
    public void checkUserLockOrder(Long userId){
        // 检测恶意取消
        Integer cancelCount = redisCache.getCacheObject(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + userId);
        if(cancelCount != null){
            Integer lockCount = sysConfigService.getValue(Config.Sys.Order.取消锁单次数);
            if(cancelCount >= lockCount){
                long expireforSeconds = redisCache.getExpireforSeconds(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + userId);
                throw new ServiceException("因24小时内取消订单达到" + lockCount + "次，" + (int)Math.ceil(expireforSeconds / 60f / 60) + "小时后才可购买");
            }
        }
    }


    /**
     * 下单
     *
     * @return
     */
    public OrderMain createOrder(@LockValue Long userId, CreateOrderDto params) {
        // 检测用户恶意锁单
        checkUserLockOrder(userId);
        String cacheOrderKey = RedisKey.KEY_USER_BOX_ORDER + params.getSourceId() + ":" + userId;
        if(params.getOrderType() == OrderTypeEnum.Box_NFT){
            OrderMain orderMain = redisCache.getCacheObject(cacheOrderKey);
            if(orderMain != null){
                return orderMain;
            }
        }
        OrderMain order = createOrderExecutor.get(params.getOrderType().getCode()).createOrder(params);
        // 保存订单
        boolean save = save(order);
        if (!save) {
            throw new ServiceException("系统忙！");
        }
        save = orderItemService.saveBatch(order.getOrderItems());
        if (!save) {
            throw new ServiceException("系统忙！");
        }
        if (Objects.nonNull(order.getAutoCancelTime())) {
            mqSender.sendDelay(AppMqDelayEnum.ORDER_CANCEL, order.getId(), order.getAutoCancelTime());
        }

        if (params.getOrderType() == OrderTypeEnum.Box_NFT) {
            redisCache.setCacheObject(cacheOrderKey, order, sysConfigService.getValue(Config.Sys.Order.订单超时时间), TimeUnit.MINUTES);
        } else if (params.getOrderType() == OrderTypeEnum.Gift) {
            // 存记录
            OrderGift orderGift = new OrderGift();
            orderGift.setOrderId(order.getId());
            orderGift.setGiftUserId(params.getGiftUserId());
            orderGift.setUserId(order.getBuyerUserId());
            orderGiftService.save(orderGift);
        }
        return order;
    }

    /**
     * 取消订单之后的后置操作
     * @param order
     */
    @Async(value = "threadPoolTaskExecutor")
    protected void cancelOrderAfter(OrderMain order){
        cleanOrderCacheInfo(order);
        recordUserCancelOrder(order);
    }

    /**
     * 清除订单缓存信息
     */
    private void cleanOrderCacheInfo(OrderMain order){
        // 清除缓存订单信息
        if(order.getOrderType() == OrderTypeEnum.Box_NFT){
            List<OrderItem> items = orderItemService.getItemsByOrderMain(order.getId());
            if(!items.isEmpty()){
                redisCache.deleteObject(RedisKey.KEY_USER_BOX_ORDER + items.get(0).getSpuId() + ":" + order.getBuyerUserId());
            }
        }
    }

    /**
     * 记录用户取消订单次数
     */
    private void recordUserCancelOrder(OrderMain order){
        // 记录用户取消订单次数
        if(order.getOrderType() != OrderTypeEnum.Recharge){
            Integer cancelCount = redisCache.getCacheObject(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + order.getBuyerUserId());
            if(cancelCount == null){
                cancelCount = 0;
            }
            cancelCount ++;
            // 从第一次取消时间开始统计，如果第一次取消之后的二十四小时，达到取消限制，则24小时内不能下单
            if(cancelCount >= sysConfigService.getValue(Config.Sys.Order.取消锁单次数)){
                redisCache.setCacheObject(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + order.getBuyerUserId(), cancelCount, 24, TimeUnit.HOURS);
            }else{
                long expireforSeconds = redisCache.getExpireforSeconds(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + order.getBuyerUserId());
                if(expireforSeconds <= 0){
                    redisCache.setCacheObject(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + order.getBuyerUserId(), cancelCount, 24, TimeUnit.HOURS);
                }else{
                    redisCache.setCacheObject(RedisKey.KEY_ORDER_CANCEL_COUNT_BY_USER + order.getBuyerUserId(), cancelCount, (int) expireforSeconds, TimeUnit.SECONDS);
                }
            }
        }
    }

    public OrderMain requireOrder(Long orderId, Long userId) {
        OrderMain order = getById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在！");
        }
        if (Objects.nonNull(userId)) {
            if (!Objects.equals(order.getBuyerUserId(), userId)) {
                // 不是该用户的订单，则返回订单不存在！
                throw new ServiceException("订单不存在！");
            }
        }
        return order;
    }

    /**
     * 获取订单统计信息
     */
    public OrderStatisticsVo getStatistics(OrderStatisticsDto params) {
        OrderStatisticsVo vo = new OrderStatisticsVo();

        return vo;
    }

    /**
     * 获取订单详情
     *
     * @return
     */
    public OrderMain getOrderDetail(Long orderId, Long userId) {
        OrderMain order = requireOrder(orderId, userId);
        // 判断订单如果是待支付，而且已经支付超时，则发起取消订单
        if (order.getStatus() == OrderStatusEnum.UN_PAY) {
            if (LocalDateTime.now().isAfter(order.getAutoCancelTime())) {
                order.setStatus(OrderStatusEnum.CLOSE);
                try {
                    cancel(orderId, null);
                } catch (Exception e) {
                }
            }
        }
        List<OrderItem> items = orderItemService.getItemsByOrderMain(order.getId());
        order.setOrderItems(items);
        return order;
    }

    /**
     * 同步订单支付状态
     *
     * @return
     */
    @RedisLock(lockKey = LockKey.LOCK_ORDER_STATUS)
    public void syncOrderPayStatus(@LockValue Long orderId, Long userId) {
        OrderMain order = requireOrder(orderId, userId);
        if (order.getStatus() == OrderStatusEnum.UN_PAY) {
            // 订单状态为未付款，则同步订单状态
            payApplyService.syncPayStatus(order.getId());
        }
    }

    /**
     * 获取订单列表
     *
     * @return
     */
    public List<OrderMain> getOrderList(WebOrderListDto params) {
        if(StringUtils.isEmpty(params.getOrderByColumn())){
            params.setOrderByColumn("id");
            params.setSortAsc(false);
        }
        params.startPageAndOrder();
        List<OrderMain> orderList = baseMapper.getOrderList(params);
        for (OrderMain orderMain : orderList) {
            List<OrderItem> items = orderItemService.getItemsByOrderMain(orderMain.getId());
            orderMain.setOrderItems(items);
        }
        return orderList;
    }

    /**
     * 获取订单列表V2
     *
     * @return
     */
    public PageList<AppOrderListVo> getOrderListV2(WebOrderListDto params) {
        Page<AppOrderListVo> page = baseMapper.getOrderListV2(Page.of(params.getPageNum(), params.getPageSize()),params);
        for (AppOrderListVo orderMain : page.getRecords()) {
            List<OrderItem> items = orderItemService.getItemsByOrderMain(orderMain.getId());
            orderMain.setOrderItems(BeanUtil.copyToList(items, AppOrderItemListVo.class));
        }
        return PageList.of(page.getRecords(), page.getTotal());
    }



    /**
     * 取消订单
     */
    @RedisLock(lockKey = LockKey.LOCK_ORDER_STATUS)
    public void cancel(@LockValue Long orderId, Long userId) {
        OrderMain order = requireOrder(orderId, userId);
        if(Objects.equals(order.getStatus(), OrderStatusEnum.CANCEL) ||
         Objects.equals(order.getStatus(), OrderStatusEnum.CLOSE)){
            // 已经取消了，则直接返回
            return;
        }
        if(BooleanUtil.isTrue(order.getException())){
            throw new ServiceException("订单异常，请联系客服！");
        }
        try{
            syncOrderPayStatus(orderId, null);
        }catch (Exception e){
        }
        orderStatusExecutor.get(OrderStatusEnum.CANCEL.getCode()).exec(order);
        mqSender.cancelDelay(AppMqDelayEnum.ORDER_CANCEL, order.getId());
        cancelOrderAfter(order);
    }

    /**
     * 关闭订单
     */
    @RedisLock(lockKey = LockKey.LOCK_ORDER_STATUS)
    public void close(@LockValue Long orderId) {
        try{
            syncOrderPayStatus(orderId, null);
        }catch (Exception e){
        }
        OrderMain order = requireOrder(orderId, null);
        if(order.getStatus() != OrderStatusEnum.UN_PAY){
            return;
        }
        if(BooleanUtil.isTrue(order.getException())){
            throw new ServiceException("订单异常，请联系客服！");
        }
        orderStatusExecutor.get(OrderStatusEnum.CLOSE.getCode()).exec(order);
        cancelOrderAfter(order);
    }

    /**
     * 支付完成
     */
    @RedisLock(lockKey = LockKey.LOCK_ORDER_STATUS, timeout = 60, waitTime = 30)
    public void payed(@LockObject(valueFields = "orderMainId") PayApply payApply) {
        OrderMain order = requireOrder(payApply.getOrderMainId(), null);
        cleanOrderCacheInfo(order);
        orderStatusExecutor.get(OrderStatusEnum.PAYED.getCode()).exec(order);
        // 更新支付信息
        update(new LambdaUpdateWrapper<OrderMain>()
                .set(OrderMain::getPayType, payApply.getPayType())
                .set(OrderMain::getActualPaymentAmount, payApply.getPayAmount())
                .set(OrderMain::getPayOrderNo, payApply.getId())
                .set(OrderMain::getPayAccount, payApply.getBuyerAccount())
                .eq(OrderMain::getId, payApply.getOrderMainId()));
    }


    /**
     * 完成订单
     */
//    @RedisLock(lockKey = LockKey.LOCK_ORDER_STATUS)
    @Transactional(rollbackFor = Exception.class)
    public void complete(@LockValue Long orderId, Long userId) {
        OrderMain order = requireOrder(orderId, userId);
        orderStatusExecutor.get(OrderStatusEnum.COMPLETED.getCode()).exec(order);
    }

    /**
     * 申请售后
     */
    @RedisLock(lockKey = LockKey.LOCK_ORDER_STATUS)
    @Transactional(rollbackFor = Exception.class)
    public void applyRefund(@LockValue Long orderId) {
        OrderMain order = requireOrder(orderId, null);
        orderStatusExecutor.get(OrderStatusEnum.REFUND.getCode()).exec(order);
    }

    /**
     * 获取商品下单数量
     *
     * @return
     */
    public int getSpuOrderCount(Long userId, Long spuId, boolean isPriority) {
        return getBaseMapper().countByUserSpuOrder(userId, spuId, isPriority);
    }

    /**
     * 更新退款状态
     *
     * @param orderMainId
     * @param refundStatus
     */
    public void updateRefundStatus(Long orderMainId, RefundStatusEnum refundStatus) {
        LambdaUpdateWrapper<OrderMain> updateWrapper = new LambdaUpdateWrapper<OrderMain>()
                .set(OrderMain::getRefundStatus, refundStatus)
                .eq(OrderMain::getId, orderMainId);
        if (refundStatus == RefundStatusEnum.CANCEL || refundStatus == RefundStatusEnum.ABORT) {
            updateWrapper.set(OrderMain::getStatus, OrderStatusEnum.COMPLETED);
        }
        update(updateWrapper);
    }

    /**
     * 标记订单异常！
     * @param orderMainId
     */
    public void exception(Long orderMainId) {
        update(new LambdaUpdateWrapper<OrderMain>()
                .set(OrderMain::getException, true)
                .eq(OrderMain::getId, orderMainId));
    }

    /**
     * 结算市场订单
     * @param orderId
     */
    @RedisLock(lockKey = LockKey.LOCK_ORDER_STATUS)
    @Transactional(rollbackFor = Exception.class)
    public void settleMarketOrder(@LockValue Long orderId) {
        OrderMain orderMain = getById(orderId);
        if(orderMain == null){
            throw new ServiceException("订单不存在：" + orderId);
        }
        if(orderMain.getStatus() != OrderStatusEnum.COMPLETED){
            throw new ServiceException("订单状态异常：" + orderId);
        }
        if(BooleanUtils.isNotTrue(orderMain.getIsSettle())){
            update(new LambdaUpdateWrapper<OrderMain>()
                    .set(OrderMain::getIsSettle, true)
                    .eq(OrderMain::getIsSettle, false)
                    .eq(OrderMain::getId, orderId));
            // 1. 给卖家增加增加资产
            BigDecimal totalAmount = orderMain.getTotalAmount();
            BigDecimal transactionFee = orderMain.getTransactionFee();
            BigDecimal sellerUserIncome = totalAmount.subtract(transactionFee);

            if(sellerUserIncome.compareTo(BigDecimal.ZERO) < 0){
                // 如果计算出来卖家收入小于0，则将卖家收入置为0
                sellerUserIncome = BigDecimal.ZERO;
            }
            // 如果是易宝支付，需要分账，但是没有开通的话就还是默认给卖家增加资产
            switch (orderMain.getPayType()){
                case YeePay_JH:
                case YeePay_Wallet:
                case YeePay_Alipay:
                    if (yeepayWalletService.getUserWallet(orderMain.getSellerUserId()) != null) {
                        orderDivideService.yeePayDivideApply(orderMain, sellerUserIncome);
                        break;
                    }
                default:{
                    userWalletService.increase(orderMain.getSellerUserId(), UserWalletEnum.CASH, sellerUserIncome, WalletChangeTypeEnum.MARKET_INCOME, orderMain.getId(), WalletChangeTypeEnum.MARKET_INCOME.getMsg());
                    // 2. 给0号账户增加资产
                    userWalletService.increase(0L, UserWalletEnum.CASH, transactionFee, WalletChangeTypeEnum.MARKET_SERVICE, orderMain.getId(),  WalletChangeTypeEnum.MARKET_SERVICE.getMsg());
                    break;
                }
            }
        }
    }

    /**
     * 订单导出（充值订单，市场订单，藏品宝盒订单）
     * @param params
     * @return
     */
    public List<AppOrderListExportVo> export(WebOrderListDto params) {
        if(StringUtils.isEmpty(params.getOrderByColumn())){
            params.setOrderByColumn("id");
            params.setSortAsc(false);
        }
        params.startOrder();
        params.setPageSize(null);
        List<AppOrderListExportVo> exportVos = baseMapper.export(params);
        return exportVos;
    }

    /**
     * 开启快速抄货
     * @param dto
     * @return
     */
    public String openQuickCopy(OpenQuickCopyDto dto,Long userId) {
        Boolean isWhiteList = orderQuickCopyRecordService.getIsWhiteList(userId);
        if (!isWhiteList){
            throw new ServiceException("当前用户不具备快速抄货权限,无法开启快速抄货");
        }
        // 支付密码校验
        sysUserService.checkPayPwd(userId, dto.getPayPwd());
        // 余额校验
        SysUserWallet giveWallet = sysUserWalletService.getWallet(userId, UserWalletEnum.CASH);
        // 快速抄货最低金额配置
        Integer value = sysConfigService.getValue(Config.Sys.Market.开启快速抄货最低金额);
        // 余额少于配置金额不可开启
        if (giveWallet.getAmount().compareTo(BigDecimal.valueOf(value)) <0){
            String str = String.format("开启免密支付,平台钱包余额需要大于%d元",value);
            throw new ServiceException(str);
        }
        // 生成的token
        String token = UUID.randomUUID().toString();
        OrderQuickCopyRecord quickCopyRecord = new OrderQuickCopyRecord();
        quickCopyRecord.setOpenTime(new Date());
        quickCopyRecord.setUserId(userId);
        quickCopyRecord.setToken(token);
        // 保存记录
        orderQuickCopyRecordService.save(quickCopyRecord);
        return token;
    }

    /**
     * 快速抄货
     * @param request
     */
//    @Transactional(rollbackFor = Exception.class)
    public R quickCopyPay(QuickCopyDto dto, Long userId, HttpServletRequest request) {
        // token验证 仅检查是否是最新的
        String copyToken = dto.getQuickCopyToken();
        LambdaQueryWrapper<OrderQuickCopyRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderQuickCopyRecord::getUserId,userId).last("limit 1").orderByDesc(OrderQuickCopyRecord::getOpenTime);
        OrderQuickCopyRecord orderQuickCopyRecord = orderQuickCopyRecordService.getBaseMapper().selectOne(wrapper);
        String token = orderQuickCopyRecord.getToken();
        if (!token.equals(copyToken)){
            throw new ServiceException("购买失败,请重新开启快速抄货");
        }
        dto.setPrice(dto.getPrice().setScale(2, RoundingMode.HALF_UP));
        // 下单
        CreateOrderDto params = new CreateOrderDto();
        params.setOrderType(OrderTypeEnum.Market);
        params.setToken(dto.getToken());
        params.setPrice(dto.getPrice());
        params.setQuantity(dto.getQuantity());
        params.setSourceId(dto.getMarketId());
        OrderMain order = createOrder(userId, params);
        AppOrderListVo vo = orderConverter.toAppOrderListVo(order);
        vo.setPayType(PayTypeEnum.Wallet);
        // 支付申请
        PayInfoVo payInfoVo;
        try {
            payInfoVo = payApplyService.applyPay(vo.getId(), userId, vo.getPayType());
        } catch (ServiceException e) {
            if(Objects.equals(e.getCode(), HttpStatus.Insufficient_Balance)){
                // 余额不足特殊处理。
                throw new ServiceException("余额不足，请更换购买");
            }
            throw e;
        }
        WalletPayDto walletPayDto = new WalletPayDto();
        walletPayDto.setPayInfo(payInfoVo.getPayInfo());
        walletPayDto.setOrderId(payInfoVo.getOrderId());
        walletPayDto.setPrice(payInfoVo.getPrice());
        walletPayDto.setTradeId(payInfoVo.getTradeId());
        walletPayDto.setIsCheckPwd(false);
        TradeResultDto tradeResultDto;
        try{
            tradeResultDto = walletPayExecutor.verifyCallback(request, walletPayDto);
        }catch (ServiceException e){
            if(Objects.equals(e.getCode(), HttpStatus.Insufficient_Balance)){
                // 余额不足特殊处理。
                throw new ServiceException("余额不足，请更换购买");
            }
            throw e;
        }
        payApplyService.paySuccess(tradeResultDto);
        // 保存快速抄货购买记录
        QuickCopyRecord quickCopyRecord = new QuickCopyRecord();
        quickCopyRecord.setUserId(userId);
        quickCopyRecord.setOrderMainId(payInfoVo.getOrderId());
        quickCopyRecord.setPayApplyId(payInfoVo.getTradeId());
        quickCopyRecord.setCreatTime(new Date());
        quickCopyRecordMapper.insert(quickCopyRecord);
        // 返回购买完成剩下的余额
        SysUserWallet wallet = userWalletService.getWallet(userId, UserWalletEnum.CASH);
        BigDecimal amount = wallet.getAmount();
        Integer value = sysConfigService.getValue(Config.Sys.Market.开启快速抄货最低金额);
        if (amount.compareTo(BigDecimal.valueOf(value))<0){
            String str = String.format("免密支付成功,您当前余额小于%d元,已关闭快速抄货",value);
           return R.ok(amount,str);
        }
        return R.ok(amount,"免密支付成功");
    }
}
